package com.eagle.security.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;

import com.eagle.security.entries.User;


public class SecurityUtils
{
    public static SecurityContextHolderAwareRequestWrapper getRequestHanndler(HttpServletRequest request)
    {
        return request instanceof SecurityContextHolderAwareRequestWrapper ? (SecurityContextHolderAwareRequestWrapper) request : new SecurityContextHolderAwareRequestWrapper(
                request, null);
    }

    /**
     * 针对当前用户，获取权限验证对象
     * 
     * @return SecurityExpressionRoot
     */
    public static SecurityExpressionRoot getSecurity()
    {
        User user = getCurrentUser();
        return user != null ? user.getSecurity() : null;
    }

    /**
     * 针对当前用户，是否拥有指定权限
     * 
     * @param role
     * @return true 拥有；false 不拥有
     */
    public static boolean hasRole(String role)
    {
        User user = getCurrentUser();
        return user != null && user.hasRole(role);
    }

    /**
     * 针对当前用户，是否拥有的指定的一个或多个权限
     * 
     * @param roles
     *            一个或多个权限名称
     * @return true 拥有；false 不拥有
     */
    public static boolean hasRoles(String... roles)
    {
        User user = getCurrentUser();
        return user != null && user.hasRoles(roles);
    }

    /**
     * 针对当前用户，是否至少拥有指定的一个或多个权限中的一个
     * 
     * @param roles
     *            一个或多个权限名称
     * @return true 拥有；false 不拥有
     */
    public static final boolean hasAnyRole(String... roles)
    {
        User user = getCurrentUser();
        return user != null && user.hasAnyRole(roles);
    }

    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 针对当前用户，判断是否登录
     * 
     * @return true 登录；false 没有登录/匿名用户
     */
    public static boolean isLogin()
    {
        return getCurrentUser() != null;
    }

    /**
     * 针对当前用户，获取用户对象
     * 
     * @return User
     */
    public static User getCurrentUser()
    {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth != null && (auth.getPrincipal() instanceof User))
        {
            return (User) auth.getPrincipal();
        }

        // return auth.getPrincipal().toString();//"anonymousUser"
        return null;
    }

    /**
     * 针对当前用户，获取用户名ID
     * 
     * @return 用户名
     */
    public static String getCurrentUserId()
    {
        User user = getCurrentUser();
        return user != null ? user.getUsername() : null;
    }
}
